import os
import time
import utime
import network
from machine import Pin
from machine import ADC
from machine import Timer
import uos
import ujson
from machine import RTC
import urequests
p_motor = Pin(16, Pin.OUT)    # create output pin on GPIO0
p_led = Pin(2, Pin.OUT)       # create output pin on GPIO0
plant_adc = ADC(0)            # create ADC object on ADC pin
timer1 = Timer(1)
SET_FILE_PATH = 'plant_set.txt'
HIS_DATA_MAX = 288# 10MIN 一个数据 大概48小时


class  plant_class:
	def __init__(self):
		self.relay_on_ct = 0
		self.poll_ct = 0
		self.humidity_avg = 0
		self.set_hmdt_val = 450 #判断阈值,超过450浇水
		self.set_push_period = 60 #数据上报周期
		self.set_push_ip = "192.168.2.126"#数据上报服务器地址设置
		self.set_motor_peroid = 60 #浇水间隔
		self.set_change = 0 #发生改动时改为5，等5s后自动保存到flash
		self.hmdt_ct = 0
		self.humidity_arr={}
		self.humidity_arr[0]=0
		self.humidity_arr[1]=0
		self.humidity_arr[2]=0
		self.his_cur_tm = 0 #最近更新数据时间戳
		self.motor_cur_tm = 0 #最近浇水时间
		# self.hist_data_10min=[0]#
	def  plant_get_humidity(self):
		global  plant_adc
		adc_v = plant_adc.read()              # read value, 0-1024
		print(utime.time(),":soil humidity=", adc_v)
		return  adc_v
	def  motor_ctrl(self, param):
		global p_motor
		if param == 1:
			print("start motor")
			p_motor.on()  # set pin to "on" (high) level
			self.relay_on_ct+=1;
		else:
			print("stop motor")
			p_motor.off()
	def  plant_set_save(self):
		self.set_change = 5
	def  plant_set_sync(self):		
		ctx_json={}
		ctx_json['set_hmdt_val']=str(self.set_hmdt_val)
		ctx_json['set_push_ip']=str(self.set_push_ip)
		ctx_json['set_push_period']=str(self.set_push_period)
		print("save init", ujson.dumps(ctx_json))
		f = open(SET_FILE_PATH, 'w')  #  打开文件进行写入
		f.write(ujson.dumps(ctx_json))# 写入内容
		f.close()# 关闭文件
	def  plant_set_load(self):
		# 检测文件是否存在
		try:
			uos.stat(SET_FILE_PATH)
			print("file exist")
			
			f = open(SET_FILE_PATH, 'r')  # 打开文件进行读取
			content = f.read()# 读取文件内容
			f.close()# 关闭文件
			# 处理读取到的内容
			# print(content)
			json_data = ujson.loads(content)
			self.set_hmdt_val = int(json_data["set_hmdt_val"])
			self.set_push_ip = json_data["set_push_ip"]
			self.set_push_period = int(json_data["set_push_period"])
			print("load set,humidity, ip,period",self.set_hmdt_val,self.set_push_ip,self.set_push_period)
		except OSError:
			print("file no exist,init setting ")
			self.set_hmdt_val = 400
			self.set_push_ip = ""
			self.set_push_period = 300
			self.plant_set_save();

	def  peroid_push(self, humdty):
		rtc_time = self.get_timestamp()
		if rtc_time - self.his_cur_tm > self.set_push_period:#600: #每隔10分钟记录一次历史数据
			self.his_cur_tm = rtc_time
			self.plant_event_push(humdty, 0)#push
	def  peroid_motor(self):
		hour_t = self.get_rtc_hour()
		if hour_t>=7 and hour_t <=18:
			rtc_time = self.get_timestamp()
			if rtc_time - self.motor_cur_tm > 3600:#600: #每隔60分钟浇水
				self.motor_cur_tm = rtc_time
				self.motor_ctrl(1)
				global timer1
				timer1.init(period=1700,mode=Timer.ONE_SHOT,callback=callback_close)
				self.plant_event_push(self.humidity_avg, 1);#浇水发送记录
			#如果土壤干燥超过设定值，并且距离上次浇水超过半小时，启动一次浇水
			# if self.humidity_avg > self.set_hmdt_val and rtc_time - self.motor_cur_tm > 1800:
			# 	print("启动一次浇水")
			#记录最近3次浇水湿度值， 如果浇水3次。湿度没有变化，则断定为没有水了
			# if  1:

	def get_timestamp(self):
		rtc = RTC()
		year, month, day, weekday, hour, minute, second, subsecond = rtc.datetime()
		rtc_time = utime.mktime((year+30, month, day, hour, minute, second, 0, 0))#年份使用2000+
		rtc_time -= 8*3600
		return rtc_time
	def get_rtc_hour(self):
		rtc = RTC()
		year, month, day, weekday, hour, minute, second, subsecond = rtc.datetime()
		return  hour;
	def  plant_event_push(self, hmdty_str,motor):
		# 网址
		tm_str=self.get_timestamp()
		if len(self.set_push_ip) > 0:
			url = "http://"+self.set_push_ip+"/plant_sql.php/ins=0?humidity="
			url = url +str(hmdty_str)+"&&tm="+str(tm_str)+"&&motor="+str(motor)
			print("geturl=", url)
			try:
				response = urequests.get(url)
				content = response.text
				print(content)
			except Exception as e:
				# 在这里处理请求失败或其他异常时的逻辑
				print("urequests.get:", e)
		else:
			print("push server ip is null")
# 定义定时器回调函数
def callback_close(timer):
    print("Timer triggered!")
    p_motor.off()
def run_poll_set_sync_1s(plant):
	if plant.set_change > 0:
		plant.set_change -= 1
		print("set change=", plant.set_change)
		if plant.set_change == 0:
			plant.plant_set_sync()
			# plant.set_change = 0# 修改为0
def run_poll_ms(plant):
	plant.poll_ct+=1
	if plant.poll_ct % 100 == 0:
		run_poll_set_sync_1s(plant)
	if plant.poll_ct >= 1500:#100次读取一次湿度判断
		plant.poll_ct = 0

		#读取三次湿度求平均值
		plant.humidity_arr[plant.hmdt_ct]=plant.plant_get_humidity()
		hmt = 0 #临时值
		hmt += plant.humidity_arr[0]
		hmt += plant.humidity_arr[1]
		hmt += plant.humidity_arr[2]
		plant.humidity_avg = hmt / 3
		print(time.time,"hmdt_avg=", plant.humidity_avg)

		plant.peroid_push(plant.humidity_avg)#定时上报
		plant.peroid_motor()#定时浇水
		# plant.hmdt_ct+=1;
		# if plant.hmdt_ct >=2:
		# 	plant.hmdt_ct = 0#三次计数清零
		# 	if plant.humidity_avg > plant.set_hmdt_val:#三次平均值大于600,启动电机1.5s后自动关闭
		# 		plant.motor_ctrl(1)
		# 		global timer1
		# 		timer1.init(period=1500,mode=Timer.ONE_SHOT,callback=callback_close)
		# 		plant.plant_event_push(plant.humidity_avg, 1);#浇水发送记录
def  main_poll():
	tt = ""
	# plant = plant_class()
	# plant.plant_set_load()

	# while 1:
	# 	run_poll_ms(plant)
	# 	time.sleep_ms(10)
#Automatic watering system ，自动浇花
# if __name__ == '__main__':
# 	main_poll()
